import playerDataInfo from "./playerData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class audioMgr extends cc.Component {
    static audioData;
    static gameMusicId;
    static initData() {
        audioMgr.audioData = {};
        audioMgr.preloadMusic()
    }

    //预加载背景音乐
    static preloadMusic() {
        audioMgr.onLodeAudioRes("music", audioMgr.saveGameAudio.bind(this), "start");
    }

    //播放音效 如果没有就加载
    static playGameAudio(name) {
        if (name != "music") {
            //是否开启背景音乐
            //@ts-ignore
            if (playerDataInfo.gameData.isMusic != 1) return
        }
        else {
            //是否开启音效
            //@ts-ignore
            if (playerDataInfo.gameData.isSound != 1) return
        }

        if (audioMgr.audioData[name]) {
            //不是背景音乐
            if (name.indexOf("music") != -1) {
                console.log("musicState: " + cc.audioEngine.isLoop(audioMgr.gameMusicId));
                if (cc.audioEngine.isLoop(audioMgr.gameMusicId)) return;
                audioMgr.gameMusicId = cc.audioEngine.play(audioMgr.audioData[name], false, 1);
                cc.audioEngine.setLoop(audioMgr.gameMusicId, true);
            }
            else {
                cc.audioEngine.play(audioMgr.audioData[name], false, 1);
            }
        }
        else {
            this.onLodeAudioRes(name, audioMgr.saveGameAudio.bind(audioMgr));
        }
    }

    //加载音效
    static onLodeAudioRes(url, callback, type = "play") {
        let self = this;
        let path = "audio/" + url
        //@ts-ignore
        cc.resources.load(path, cc.audioEngine, (err, audio) => {
            if (!err) callback(audio, type);
            else console.log("load audio err: ", err);
        })
    }

    //保存音效
    static saveGameAudio(audio, audioName, type = "play") {
        audioMgr.audioData[audioName] = audio;
        if (type != "start") audioMgr.playGameAudio(audioName);
    }

    //停止播放
    static stopGameAudio(name) {
        cc.audioEngine.stop(audioMgr.gameMusicId);
    }
}
